package middleware

import (
	"fmt"

	loader "github.com/joshua-liu-github/dynamic-conf/loader"
	nacosCli "github.com/joshua-liu-github/dynamic-conf/middleware/nacos"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	log "github.com/sirupsen/logrus"
)

// The StoreClient interface is implemented by objects that can retrieve
// key/value pairs from a backend store.
type StoreClient interface {
	GetContent(dataId string, group string) (string, error)
	WatchContent(dataId string, group string, cbk func(dataId string, group string, content string)) (int, error)
}

var globalConfig = loader.GlobalConfig

func New() (StoreClient, error) {
	serverAddr := globalConfig.GetString("application.config.nacos.server-addr")
	namespace := globalConfig.GetString("application.config.nacos.namespace")
	username := globalConfig.GetString("application.config.nacos.username")
	password := globalConfig.GetString("application.config.nacos.password")
	log.Info(fmt.Sprintf("Nacos server addr: '%s',namespace: '%s', username: '%s' \n",
		serverAddr, namespace, username))
	hosts := []string{serverAddr}
	cli, err := nacosCli.NewNacosClient(hosts, constant.ClientConfig{
		NamespaceId: namespace,
		Username:    username,
		Password:    password,
		LogLevel:    "error",
	})
	if err != nil {
		log.Error(fmt.Sprintf("Nacos server addr: '%s'\n", err))
	}
	return cli, err
}
